package vn.edu.ptithcm.pim.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import vn.edu.ptithcm.pim.constant.Constants;
import vn.edu.ptithcm.pim.constant.UrlConstants;
import vn.edu.ptithcm.pim.dom.Employee;
import vn.edu.ptithcm.pim.dom.Project;
import vn.edu.ptithcm.pim.dom.Task;
import vn.edu.ptithcm.pim.query.TaskQuery;
import vn.edu.ptithcm.pim.service.EmployeeService;
import vn.edu.ptithcm.pim.service.PhaseService;
import vn.edu.ptithcm.pim.service.ProjectService;
import vn.edu.ptithcm.pim.service.TaskCategoryService;
import vn.edu.ptithcm.pim.service.TaskPriorityService;
import vn.edu.ptithcm.pim.service.TaskService;
import vn.edu.ptithcm.pim.service.TaskSeverityService;
import vn.edu.ptithcm.pim.service.TaskStatusService;
import vn.edu.ptithcm.pim.service.UserService;
import vn.edu.ptithcm.pim.util.ParamUtil;

@SuppressWarnings({ "deprecation", "rawtypes" })
public class MyTasksController extends SimpleFormController {

	private TaskService taskService;
	private UserService userService;
	private TaskSeverityService taskSeverityService;
	private TaskCategoryService taskCategoryService;
	private TaskPriorityService taskPriorityService;
	private TaskStatusService taskStatusService;
	private ProjectService projectService;
	private EmployeeService employeeService;
	private PhaseService phaseService;

	public MyTasksController() {
		super();
		setSessionForm(true);
		setCommandName("taskQuery");
		setCommandClass(TaskQuery.class);
		setFormView(UrlConstants.MY_TASKS_URL);
		setSuccessView(UrlConstants.MY_TASKS_URL);
	}

	@Override
	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {
		return new TaskQuery();
	}

	@Override
	public void initBinder(HttpServletRequest request,
			ServletRequestDataBinder binder) throws Exception {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		binder.registerCustomEditor(Date.class, new CustomDateEditor(
				dateFormat, true));
	}

	@Override
	protected ServletRequestDataBinder createBinder(HttpServletRequest request,
			Object command) throws Exception {
		TaskQuery informTaskQuery = (TaskQuery) command;
		if (userService.isSignedIn(request)) {
			String loginName = userService.getCurrentLogin(request);
			informTaskQuery.setAssignedto(userService
					.findByLoginName(loginName).getEmployee().getVisa());
		}
		return super.createBinder(request, informTaskQuery);
	}

	@Override
	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		TaskQuery informTaskQuery = (TaskQuery) command;
		String cmd = ParamUtil.getString(request, "cmd", "");
		if (cmd.equals(Constants.FILTER)) {
			int pnum = ParamUtil.getInteger(request, "pnum", 0);
			Project project = projectService.findByNumber(pnum);
			if (project != null) {
				request.setAttribute(
						"tasks",
						taskService.findByQuery(informTaskQuery,
								project.getProjectid()));
			}
		} else if (cmd.equals(Constants.RESET)) {
			informTaskQuery.setReporter("");
			informTaskQuery.setCategoryId(new Long(0));
			informTaskQuery.setHideStatusId(new Long(0));
			informTaskQuery.setItemsPerPage(new Integer(0));
			informTaskQuery.setPhase("");
			informTaskQuery.setPriorityId(new Long(0));
			informTaskQuery.setSeverityId(new Long(0));
			informTaskQuery.setShowStatusId(new Long(0));
			informTaskQuery.setStarttime(null);
			informTaskQuery.setEndtime(null);
			String loginName = userService.getCurrentLogin(request);
			if (loginName != null) {
				informTaskQuery.setAssignedto(userService
						.findByLoginName(loginName).getEmployee().getVisa());
			}
		}
		return showForm(request, response, errors);
	}

	@SuppressWarnings("unchecked")
	@Override
	protected ModelAndView showForm(HttpServletRequest request,
			HttpServletResponse response, BindException errors)
			throws Exception {
		Map<String, Object> bean = new HashMap<String, Object>();
		if (userService.isSignedIn(request)) {
			String loginName = userService.getCurrentLogin(request);
			bean.put("user", userService.findByLoginName(loginName));
			bean.put("isSigned", true);
			bean.put(Constants.LOGIN_NAME, loginName);
			bean.put(Constants.USER_NAME, userService.getUsername(loginName));
			bean.put("isAdmin", userService.isAdmin(loginName));
			String visa = userService.getVisa(loginName);
			int pnum = ParamUtil.getInteger(request, "pnum", 0);
			Project project = projectService.findByNumber(pnum);
			bean.put("project", project);
			bean.put("tab", "mytasks");
			Employee employee = employeeService.findByVisa(visa);

			String returnToFullPageURL = ParamUtil.getString(request,
					Constants.RETURN_TO_FULL_PAGE_URL, "");

			if (returnToFullPageURL.isEmpty()) {
				returnToFullPageURL = request.getHeader("referer");
			}
			bean.put(Constants.RETURN_TO_FULL_PAGE_URL, returnToFullPageURL);
			bean.put("severities", taskSeverityService.getAll());
			bean.put("categories", taskCategoryService.getAll());
			bean.put("priorities", taskPriorityService.getAll());
			bean.put("statuses", taskStatusService.getAll());
			bean.put("phases", phaseService.getAll());
			bean.put("tab", "mytasks");

			List<Integer> items = new ArrayList<Integer>();
			items.add(20);
			items.add(30);
			items.add(50);
			items.add(75);
			items.add(100);
			bean.put("items", items);

			List<Task> tasks = new ArrayList<Task>();
			if (project != null && employee != null) {
				bean.put("members",
						projectService.getAllMembers(project.getProjectid()));
				if (request.getAttribute("tasks") == null) {
					tasks = projectService.getUnResolvedTasks(
							employee.getVisa(), project.getProjectid(), 20, 0);
				} else {
					tasks = (List) request.getAttribute("tasks");
				}
			}
			bean.put("tasks", tasks);
			bean.put("countList", tasks.size());

			request.setAttribute("bean", bean);
		} else {
			int pnum = ParamUtil.getInteger(request, "pnum", 0);
			String redirectLink = UrlConstants.MY_TASKS_URL + UrlConstants.HTM
					+ "?pnum=" + pnum;
			request.getSession().setAttribute("redirectLink", redirectLink);
			response.sendRedirect(UrlConstants.HOME_PAGE_URL + UrlConstants.HTM);
		}
		return super.showForm(request, response, errors);
	}

	public TaskService getTaskService() {
		return taskService;
	}

	public void setTaskService(TaskService taskService) {
		this.taskService = taskService;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public TaskSeverityService getTaskSeverityService() {
		return taskSeverityService;
	}

	public void setTaskSeverityService(TaskSeverityService taskSeverityService) {
		this.taskSeverityService = taskSeverityService;
	}

	public TaskCategoryService getTaskCategoryService() {
		return taskCategoryService;
	}

	public void setTaskCategoryService(TaskCategoryService taskCategoryService) {
		this.taskCategoryService = taskCategoryService;
	}

	public TaskPriorityService getTaskPriorityService() {
		return taskPriorityService;
	}

	public void setTaskPriorityService(TaskPriorityService taskPriorityService) {
		this.taskPriorityService = taskPriorityService;
	}

	public TaskStatusService getTaskStatusService() {
		return taskStatusService;
	}

	public void setTaskStatusService(TaskStatusService taskStatusService) {
		this.taskStatusService = taskStatusService;
	}

	public ProjectService getProjectService() {
		return projectService;
	}

	public void setProjectService(ProjectService projectService) {
		this.projectService = projectService;
	}

	public EmployeeService getEmployeeService() {
		return employeeService;
	}

	public void setEmployeeService(EmployeeService employeeService) {
		this.employeeService = employeeService;
	}

	public PhaseService getPhaseService() {
		return phaseService;
	}

	public void setPhaseService(PhaseService phaseService) {
		this.phaseService = phaseService;
	}

}
